import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig(({ mode }) => {
  // 加载 .env 文件中的环境变量
  const env = loadEnv(mode, process.cwd())
  
  return {
    plugins: [vue()],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      host: true,
      port: 5173,
      strictPort: true,
      hmr: {
        timeout: 5000
      },
      proxy: {
        '/api': {
          target: env.VITE_DIFY_API_URL,
          changeOrigin: true,
          secure: false,
          rewrite: path => path.replace(/^\/api/, ''),
          configure: (proxy, options) => {
            // 处理请求
            proxy.on('proxyReq', (proxyReq, req, res) => {
              // 如果是OPTIONS请求，直接处理不转发
              if (req.method === 'OPTIONS') {
                res.writeHead(200, {
                  'Access-Control-Allow-Origin': '*',
                  'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
                  'Access-Control-Allow-Headers': 'Content-Type, Authorization, Accept',
                  'Access-Control-Max-Age': '1728000'
                })
                res.end()
                return true // 阻止继续处理
              }
            })

            proxy.on('proxyRes', (proxyRes, req, res) => {
              // 设置CORS头
              res.setHeader('Access-Control-Allow-Origin', '*')
              res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
              res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Accept')
            })

            proxy.on('error', (err, req, res) => {
              console.error('代理错误:', err)
              if (res && typeof res.headersSent !== 'undefined' && !res.headersSent) {
                try {
                  res.writeHead(500, {
                    'Content-Type': 'application/json'
                  })
                  res.end(JSON.stringify({ error: '代理请求失败', message: err.message }))
                } catch (writeError) {
                  console.error('无法写入错误响应:', writeError)
                }
              }
            })
          }
        }
      }
    }
  }
}) 